<?php
/**
 * 验证码生成类
 * @author Bun <bunwong@qq.com>
 */
class PosterModel extends BpfServiceModel
{
  private $_font;
  private $_reportPng;
  private $recommend_bj;
  private $recommend_k;
  private $recommend_c;


  protected function __init()
  {
    $resourceFile = dirname(__FILE__) . '/resources';
    $this->_font = "{$resourceFile}/1.ttf";
    $this->_reportPng = "{$resourceFile}/report.png";
    $this->recommend_bj = "{$resourceFile}/recommend_bj.png";
    $this->recommend_k = "{$resourceFile}/recommend_k.png";
  }

  protected function emoji_filter($nickname) {
    $nickname = preg_replace('/[\x{1F600}-\x{1F64F}]/u', '', $nickname);
    $nickname = preg_replace('/[\x{1F300}-\x{1F5FF}]/u', '', $nickname);
    $nickname = preg_replace('/[\x{1F680}-\x{1F6FF}]/u', '', $nickname);
    $nickname = preg_replace('/[\x{2600}-\x{26FF}]/u', '', $nickname);
    $nickname = preg_replace('/[\x{2700}-\x{27BF}]/u', '', $nickname);
    $nickname = str_replace(array('"','\''), '', $nickname);
    return $nickname;
}

  public function report($data = [])
  {
   # code...
    $name = $data['name'] ?? '';
    $playerId = $data['player_id'] ?? '';
    $datas = $data['datas'] ?? [];
    $visitor = intval($data['visitor'] ?? 0);
    $flowers = intval($data['flowers'] ?? 0);
    $allrank = intval($data['allrank'] ?? 0);
    if (strlen($name) > 15) {
      $name = substr($name, 0, 15) . '...';
    }
    $image = imagecreatefromstring(file_get_contents($this->_reportPng));
    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 86, 85, 81);
    $titie =  $name . '的香氛店经营周报';

    $width = imagesx ($image);
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    $textoffset = ceil(($width - $textWidth) / 2); //计算文字的水平位置
    imagefttext($image, $fontSize, 0, $textoffset, 380, $black, $this->_font, $titie);

    if (!empty($datas) && ($h = (200 / max($datas)))) {
      //计算点
      imagesetthickness($image, 4);
      $lastPoint = ['x' => 80, 'y' => 680];
      $step = 75;
      foreach ($datas as $key => $data) {
        $point = [ 'x' => $lastPoint['x'] + $step, 'y' => 680 - ($data * $h)];
        if ($key) {
          imageline($image, $lastPoint['x'], $lastPoint['y'] ,$point['x'], $point['y'], $white);
        }
        $lastPoint = $point;
      }
    }

    $titie = '七日营业额变化趋势';
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    $textoffset = ceil(($width - $textWidth) / 2); //计算文字的水平位置
    imagefttext($image, $fontSize, 0, $textoffset, 770, $black, $this->_font, $titie);

    $titie = '上周访客数量：' . $visitor;
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 120, 1020, $black, $this->_font, $titie);

    $titie = '上周创收鲜花数量：' . $flowers;
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 120, 1100, $black, $this->_font, $titie);

    $titie = '全服排名：' . $allrank;
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 120, 1180, $black, $this->_font, $titie);

    //画白色条纹
    imagefilledrectangle($image, 0, 1300, $width, 1400, $white);

    //添加文字
    $titie = '识别小程序码';
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 110, 1360, $black, $this->_font, $titie);

    $titie = '全民一起来开店！';
    $fontSize = 25;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 450, 1360, $black, $this->_font, $titie);

    $qrImage = imagecreatefromstring($this->getModel('miniprogram')->getWxaCodeunLimit('pages/index/main', "playerId={$playerId}&parentId={$playerId}"));
    $qrImageWidth = imagesx ($qrImage);
    $qrImageHeight = imagesy ($qrImage);
    $newQrImageWidth = 100;
    $scale = $qrImageWidth / $newQrImageWidth;
    $newQrImageHeight = $qrImageHeight / $scale;
    $qrLeftOffest = ($width - $newQrImageWidth) / 2;
    imagecopyresampled ($image, $qrImage, $qrLeftOffest, 1300, 0, 0, $newQrImageWidth, $newQrImageHeight, $qrImageWidth, $qrImageHeight);
    header('Content-Type:image/jpg');
    imagejpeg($image);
    imagedestroy($image);
  }


  private function getImage($url)
  {
    $cacheid = 'poster-' . md5($url);
    $file = VARPATH . '/' . $cacheid;
    if (file_exists($file)) {
      return imagecreatefrompng($file);
    }
    $png8 = imagecreatefromstring( file_get_contents($url) );
    if (!imageistruecolor($png8)) {
      $width = imagesx ($png8);
      $height = imagesy ($png8);
      $image = imagecreatetruecolor($width, $height);
      $transparentIndex = imagecolorallocatealpha($image, 255, 255, 255, 120);
      imagefill($image, 0, 0, $transparentIndex);
      imagecolortransparent($image, $transparentIndex);
      imagecopy($image, $png8, 0, 0, 0, 0, $width, $height);
    } else {
      $image = $png8;
    }
    imageSaveAlpha($image, true);
    imagepng($image, $file);
    return $image;
  }

  private function draw($image, $qrImage, $x, $y, $widthPx = 0)
  {
    $qrImageWidth = imagesx ($qrImage);
    $qrImageHeight = imagesy ($qrImage);
    $scale = $widthPx ?  $widthPx / $qrImageWidth : 1;
    // $scale = 1;
    imagecopyresampled ($image, $qrImage, $x, $y, 0, 0, $qrImageWidth * $scale, $qrImageHeight * $scale, $qrImageWidth, $qrImageHeight);
  }

  function resizeImage($im,$maxwidth = 0,$maxheight = 0) {
    $pic_width = imagesx($im);
    $pic_height = imagesy($im);
    $resizewidth_tag = false;
    $resizeheight_tag = false;
    if(($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)){
        if($maxwidth && $pic_width>$maxwidth) {
          $widthratio = $maxwidth/$pic_width;
          $resizewidth_tag = true;
        }
        if($maxheight && $pic_height>$maxheight) {
          $heightratio = $maxheight/$pic_height;
          $resizeheight_tag = true;
        }
        if($resizewidth_tag && $resizeheight_tag) {
          if($widthratio<$heightratio) {
            $ratio = $widthratio;
          } else { $ratio = $heightratio; }
        }
        if($resizewidth_tag && !$resizeheight_tag) { $ratio = $widthratio; }
        if($resizeheight_tag && !$resizewidth_tag) { $ratio = $heightratio; }
        $newwidth = $pic_width * $ratio;
        $newheight = $pic_height * $ratio;
        $newim = imagecreatetruecolor($newwidth,$newheight);
        $transparentIndex = imagecolorallocatealpha($newim, 255, 255, 255, 120);
        imagefill($newim, 0, 0, $transparentIndex);
        imagecolortransparent($newim, $transparentIndex);
        imagecopyresampled($newim,$im,0,0,0,0,$newwidth,$newheight,$pic_width,$pic_height);
        imagedestroy($im);
        return $newim;
    } else {
      return $im;
    }
  }


  public function recommend($data = [])
  {

    $titie = $this->emoji_filter($data['name'] ?? '');
    $playerId = $data['player_id'] ?? '';
    $store = $data['store'];
    $windowWidth = intval($store['windowWidth'] ?? 0);
    $image = $this->getImage($store['themeImage'] ?? '');
    //重定义背景框
    $image = $this->resizeImage($image, $windowWidth);
    foreach ($store['source'] ?? [] as $s) {
      # code...
      $simage = $this->getImage($s['image'] ?? '');
      $this->draw($image, $simage, $s['x'] ?? 100, $s['y'] ?? 100, $s['widthPx'] ?? 0);
    }

    $white = imagecolorallocate($image, 255, 255, 255);
    $black = imagecolorallocate($image, 86, 85, 81);
    $org = imagecolorallocate($image, 188, 76, 25);
    $width = imagesx ($image);
    $height = imagesy ($image);


    //加载相框
    $bjImage = imagecreatefromstring(file_get_contents($this->recommend_bj));
    $bjImage = $this->resizeImage($bjImage, $windowWidth);

    $bjImageWidth = imagesx ($bjImage);
    $bjImageHeight = imagesy ($bjImage);
    $newQrImageWidth = $bjImageWidth;
    $scale = $bjImageWidth / $newQrImageWidth;
    $newQrImageHeight = $bjImageHeight / $scale;
    $qrLeftOffest = ($width - $newQrImageWidth) / 2;
    imagecopyresampled ($image, $bjImage, 0, 0, 0, 0, $newQrImageWidth, $newQrImageHeight, $bjImageWidth, $bjImageHeight);

    //店铺名字
    $kuangImage = imagecreatefromstring(file_get_contents($this->recommend_k));
    $kwidth = imagesx ($kuangImage);
    $titie = $titie . '的香氛店';
    $fontSize = 15;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie);
    $textWidth = $info[2] - $info[0];
    $ktextoffset = 60 + ceil((220 - $textWidth) / 2); //计算文字的水平位置
    //70
    imagefttext($kuangImage, $fontSize, 0, $ktextoffset, 220, $white, $this->_font, $titie);
    $kuangImageWidth = imagesx ($kuangImage);
    $kuangImageHeight = imagesy ($kuangImage);
    $newQrImageWidth = 250;
    $scale = $kuangImageWidth / $newQrImageWidth;
    $newQrImageHeight = $kuangImageHeight / $scale;
    $qrLeftOffest = ($width - $newQrImageWidth) / 2;
    $this->draw($image, $kuangImage, 10, 25, 140);

    $textheight = $height * 0.68;

    $titie = '嘿，快来闻闻，';
    $fontSize = 18;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    $textoffset = ceil(($width - $textWidth) / 2); //计算文字的水平位置
    imagefttext($image, $fontSize, 0, $textoffset, $textheight, $org, $this->_font, $titie);

    $titie = '这是爱的味道';
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    $textoffset = ceil(($width - $textWidth) / 2); //计算文字的水平位置
    imagefttext($image, $fontSize, 0, $textoffset, $textheight + 30, $org, $this->_font, $titie);
    $titie = '长按识别小程序码';
    $fontSize = 10;
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 25, $textheight + 100, $black, $this->_font, $titie);
    $titie = '进入我的香氛店';
    $info = imageftbbox($fontSize, 0 , $this->_font , $titie );
    $textWidth = $info[2] - $info[0];
    imagefttext($image, $fontSize, 0, 250, $textheight + 100, $black, $this->_font, $titie);

    $qrImage = imagecreatefromstring($this->getModel('miniprogram')->getWxaCodeunLimit('pages/index/main', "playerId={$playerId}&parentId={$playerId}"));
    $this->draw($image, $qrImage, 140, $textheight + 50, 100);

    header('Content-Type:image/jpg');
    imagejpeg($image);
    imagedestroy($image);

  }

}
